package com.ruoyi.platform.hknet.auth;

import com.ruoyi.platform.hknet.utils.HTTPClientUtil;
import com.ruoyi.platform.hknet.utils.HttpAysncClientUtil;
import com.ruoyi.platform.hknet.utils.HttpsClientUtil;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.validator.internal.engine.messageinterpolation.parser.ELState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * @description
 * @author:Figo2020
 * @date: 2025/10/26 12:13
 */
public class HikLoginUtils {
    
    private static final Logger log = LoggerFactory.getLogger(HikLoginUtils.class);
    
    /**
     * 登录设备
     *
     * @param ip      设备IP地址
     * @param port    设备端口
     * @param username    设备用户名
     * @param password     设备密码
     * @param httpEnabled  https开启标识
     * @return 登录成功返回用户ID，失败返回-1
     */
    public static boolean loginDevice(String ip, int port, String username, String password,boolean httpEnabled) {
        
        boolean bResult=false;
        HttpsClientUtil.strIP = ip;
        HttpsClientUtil.iPort = port;
        
        HTTPClientUtil.strIP = ip;
        HTTPClientUtil.iPort = port;
        
        HttpAysncClientUtil.strIP = ip;
        HttpAysncClientUtil.iPort = port;
        HttpAysncClientUtil.HttpAysncInit(username, password);
        HttpsClientUtil.bHttpsEnabled = httpEnabled;
        if (HttpsClientUtil.bHttpsEnabled) {
            HttpsClientUtil.httpsClientInit(ip, username, password);
        } else {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            HTTPClientUtil.client.getState().setCredentials(AuthScope.ANY, creds);
            HTTPClientUtil.client.getHostConfiguration().setHost(ip, port);
        }
        
        try {
            String strOut = "";
            String url = "";
            if (HttpsClientUtil.bHttpsEnabled) {
                url = "https://" + HttpsClientUtil.strIP + ":" + HttpsClientUtil.iPort + "/ISAPI/Security/userCheck";
                strOut = HttpsClientUtil.httpsGet(url);
            } else {
                url = "/ISAPI/Security/userCheck";
                strOut = HTTPClientUtil.doGet(url);
            }
            
            SAXReader saxReader = new SAXReader();
            
            Document document = saxReader.read(new ByteArrayInputStream(strOut.getBytes("UTF-8")));
            Element employees = document.getRootElement();
            
            for (Iterator i = employees.elementIterator(); i.hasNext(); ) {
                
                Element employee = (Element) i.next();
                
                if (employee.getName() == "statusValue" && 0 == employee.getText().compareTo("200")) {
                    bResult = true;
                }
            }
            
        } catch (Exception e) {
            log.error("登录错误:::" + e.getMessage());
        }
        return bResult;
    }
    
    /**
     * 接口请求调用
     * @param url
     * @param username
     * @param password
     * @param requestMethod
     * @param httpEnabled
     * @return
     */
    public static String doRequest(String url,String username, String password,String requestMethod,String jsonString,boolean httpEnabled) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        HTTPClientUtil.client.getState().setCredentials(AuthScope.ANY, creds);
        
        try {
            String strResponseData = "";
            if(requestMethod.equalsIgnoreCase(HTTPClientUtil.HTTP_GET)){
                strResponseData = HTTPClientUtil.doGet(url);
            }else if(requestMethod.equalsIgnoreCase(HTTPClientUtil.HTTP_POST)){
                strResponseData =  HTTPClientUtil.doPost(url,jsonString);
            }else{
                strResponseData = HTTPClientUtil.doPut(url,jsonString);
            }
            //输出接收的消息
            return strResponseData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
